package server

import (
	"gc-rds-ha/internal/common"
	grpcError "gc-rds-ha/internal/error"
	"gc-rds-ha/internal/service/mysql_sync"
	msg "gc-rds-ha/scripts"

	"golang.org/x/net/context"
)

func (server *GcRdsHaServer) Commands(context.Context, *msg.ClientInfo) (*msg.SupportedInfo, error) {
	return &msg.SupportedInfo{
		Content: ``,
	}, nil
}

// OrchSync 主从同步
func (server *GcRdsHaServer) OrchSync(ctx context.Context, req *msg.STOrchSyncReq) (*msg.STOrchSyncRsp, error) {
	return mysql_sync.DoOrchSync(ctx, req)
}

// OrchSwitchMaster 切主
func (server *GcRdsHaServer) OrchSwitchMaster(ctx context.Context, req *msg.STOrchSwitchMasterReq) (*msg.STOrchSwitchMasterRsp, error) {
	if !common.IsIpAddr(req.MasterHost) || !common.IsIpAddr(req.SlaveHost) {
		return nil, grpcError.GrpcErrArgsInvalid
	}
	return mysql_sync.DoOrchSwitchMaster(req)
}

// OrchOperateOnlineStatus 主、从节点操作上下线
func (server *GcRdsHaServer) OrchOperateOnlineStatus() {

}

// SyncProxySql ProxySql方式同步mysql集群拓扑信息
func (server *GcRdsHaServer) SyncProxySql(ctx context.Context, req *msg.STSyncProxySqlReq) (*msg.STSyncProxySqlRsp, error) {
	if req.ClusterAlias == "" {
		return nil, grpcError.GrpcErrArgsInvalid
	}
	return mysql_sync.DoSyncProxySql(ctx, req)
}

// 同步RDS-MYSQL集群和实例信息
func (server *GcRdsHaServer) SyncECSClustersInfo(ctx context.Context, req *msg.STSyncECSClustersInfoReq) (*msg.STSyncECSClustersInfoRsp, error) {
	if req.MasterIp == "" || req.MasterPort <= 0 || len(req.ProxyIp) <= 0 {
		return nil, grpcError.GrpcErrArgsInvalid
	}
	return mysql_sync.DoSyncECSClustersInfo(ctx, req)
}

// 发现集群信息
func (server *GcRdsHaServer) DiscoverCluster(ctx context.Context, req *msg.STDiscoverClusterReq) (*msg.STDiscoverClusterRsp, error) {
	if req.MasterIp == "" || req.MasterPort <= 0 {
		return nil, grpcError.GrpcErrArgsInvalid
	}
	rsp, err := mysql_sync.Discover(ctx, req)
	if err != nil {
		return rsp, grpcError.GrpcErrSystem
	}
	return rsp, nil
}

func (server *GcRdsHaServer) ForgetCluster(ctx context.Context, req *msg.STDiscoverClusterReq) (*msg.STDiscoverClusterRsp, error) {
	if req.MasterIp == "" || req.MasterPort <= 0 {
		return nil, grpcError.GrpcErrArgsInvalid
	}
	rsp, err := mysql_sync.Forget(ctx, req)
	if err != nil {
		return rsp, grpcError.GrpcErrSystem
	}
	return rsp, nil
}
